<?php

/**
 * @file
 * Remove segments of a url path.
 */

$plugin = array(
  'form'     => 'feeds_tamper_ccloud_remove_url_segment_form',
  'callback' => 'feeds_tamper_ccloud_remove_url_segment_callback',
  'name' => 'CCloud: Remove segments of url attribute',
  'multi' => 'loop',
  'category' => 'HTML',
);

function feeds_tamper_ccloud_remove_url_segment_form($importer, $element_key, $settings) {
  $form = array();

  $form['tag'] = array(
    '#type' => 'textfield',
    '#title' => t('Tag'),
    '#required' => TRUE,
    '#description' => t('Such as: img'),
    '#default_value' => isset($settings['tag']) ? $settings['tag'] : '',
  );

  $form['attribute'] = array(
    '#type' => 'textfield',
    '#title' => t('Attribute'),
    '#required' => TRUE,
    '#description' => t('Such as: src'),
    '#default_value' => isset($settings['attribute']) ? $settings['attribute'] : '',
  );

  $form['included'] = array(
    '#type' => 'textfield',
    '#title' => t('String included'),
    '#description' => t('String that should appear in the url string, to make this action effective. Such as: ./'),
    '#default_value' => isset($settings['included']) ? $settings['included'] : '',
  );

  $form['indexes'] = array(
    '#type' => 'textfield',
    '#title' => t('Indexes'),
    '#required' => TRUE,
    '#description' => t('Separated by commas, such as: 0,1,2'),
    '#default_value' => isset($settings['indexes']) ? $settings['indexes'] : '',
  );

  return $form;
}

function feeds_tamper_ccloud_remove_url_segment_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  $tag = $settings['tag'];
  $attribute = $settings['attribute'];
  $included = $settings['included'];

  $indexes = $settings['indexes'];
  $indexes_array = explode(',', $indexes);

  if (preg_match_all('/<' . $tag . '[^>]+>/i', $field, $tag_matches)) {
    foreach ($tag_matches[0] as $tag_match) {
      if (preg_match('/' . $attribute . '="([^"]*)"/i', $tag_match, $attribute_match)) {
        $attribute_value = $attribute_match[1];

        if (empty($included) || strpos($attribute_value, $included) !== FALSE) {
          $segments = explode('/', $attribute_value);

          foreach ($indexes_array as $index) {
            if (!is_null($segments[$index])) {
              unset($segments[$index]);
            }
          }

          $updated_attribute_value = implode('/', $segments);
          $field = str_replace($attribute_value, $updated_attribute_value, $field);
        }
      }
    }
  }
}